"""
序列化器模块
为spider模块提供Django REST Framework序列化器
"""
from rest_framework import serializers
from .models import SubDetailItem, DetailItem, ListItem, CrawlTask


class CrawlTaskSerializer(serializers.ModelSerializer):
    """爬取任务序列化器"""
    class Meta:
        model = CrawlTask
        fields = ['id', 'url', 'task_type', 'status', 'created_at', 'updated_at', 'crawled_at']


class ListItemSerializer(serializers.ModelSerializer):
    """列表项序列化器"""
    task = CrawlTaskSerializer(read_only=True)
    
    class Meta:
        model = ListItem
        fields = [
            'id', 'title', 'url', 'publish_time', 'province', 
            'source_platform', 'business_type', 'info_type', 
            'industry', 'task', 'created_at', 'updated_at'
        ]


class DetailItemSerializer(serializers.ModelSerializer):
    """详情项序列化器"""
    list_item = ListItemSerializer(read_only=True)
    task = CrawlTaskSerializer(read_only=True)
    
    class Meta:
        model = DetailItem
        fields = [
            'id', 'project_number', 'info_source', 'list_item', 
            'task', 'sub_detail_urls', 'url', 'created_at', 'updated_at'
        ]


class SubDetailItemSerializer(serializers.ModelSerializer):
    """子详情项序列化器 - 完整版本（包含关联的DetailItem和ListItem）"""
    detail_item = DetailItemSerializer(read_only=True)
    task = CrawlTaskSerializer(read_only=True)
    
    class Meta:
        model = SubDetailItem
        fields = [
            'id', 'url', 'html_content', 'detail_item', 
            'task', 'created_at', 'return_count', 'is_processed',
            'recognized_type', 'recognized_confidence', 'recognized_reason',
            'classify_input_tokens', 'classify_output_tokens',
            'process_input_tokens', 'process_output_tokens',
            'ai_input_tokens', 'ai_output_tokens'
        ]
        # 不设置 html_content 为 write_only，因为随机API需要返回HTML内容


class SubDetailItemListSerializer(serializers.ModelSerializer):
    """子详情项序列化器 - 简化版本（用于列表显示）"""
    detail_item = serializers.SerializerMethodField()
    task = CrawlTaskSerializer(read_only=True)
    
    class Meta:
        model = SubDetailItem
        fields = [
            'id', 'url', 'detail_item', 'task', 'created_at', 'return_count', 'is_processed',
            'ai_input_tokens', 'ai_output_tokens'
        ]
    
    def get_detail_item(self, obj):
        """获取简化的详情项信息"""
        if obj.detail_item:
            return {
                'id': obj.detail_item.id,
                'project_number': obj.detail_item.project_number,
                'list_item': {
                    'id': obj.detail_item.list_item.id,
                    'title': obj.detail_item.list_item.title,
                    'province': obj.detail_item.list_item.province,
                    'business_type': obj.detail_item.list_item.business_type,
                }
            }
        return None


class SubDetailItemQuerySerializer(serializers.ModelSerializer):
    """用于查询参数验证的序列化器"""
    detail_item_id = serializers.IntegerField(required=False)
    list_item_id = serializers.IntegerField(required=False)
    task_id = serializers.IntegerField(required=False)
    project_number = serializers.CharField(required=False, max_length=200)
    province = serializers.CharField(required=False, max_length=50)
    business_type = serializers.CharField(required=False, max_length=100)
    created_after = serializers.DateTimeField(required=False)
    created_before = serializers.DateTimeField(required=False)
    limit = serializers.IntegerField(required=False, min_value=1, max_value=1000, default=100)
    offset = serializers.IntegerField(required=False, min_value=0, default=0)
    
    class Meta:
        model = SubDetailItem
        fields = [
            'detail_item_id', 'list_item_id', 'task_id', 
            'project_number', 'province', 'business_type',
            'created_after', 'created_before', 'limit', 'offset'
        ]